﻿using System.Linq;
using DataAccess.Accessors.Interfaces;
using DataAccess.DAO;
using NHibernate.Linq;

namespace DataAccess.Accessors
{
    public class SocialNetworkAccessor : ISocialNetworkAccessor
    {
        private readonly IDataAccessor _dataAccessor;

        public SocialNetworkAccessor(IDataAccessor dataAccessor)
        {
            _dataAccessor = dataAccessor;
        }

        public SocialNetworkDAO GetNetworkById(long id)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                return (from socialNetworks in session.Query<SocialNetworkDAO>()
                        where socialNetworks.SocialNetworkId == id
                        select socialNetworks).SingleOrDefault();
            }
        }

        public SocialNetworkDAO GetNetworkByName(string name)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                return (from socialNetworks in session.Query<SocialNetworkDAO>()
                        where socialNetworks.SocialNetworkName == name
                        select socialNetworks).SingleOrDefault();
            }
        }

        public void Save(SocialNetworkDAO socialNetwork)
        {
            using (var session = _dataAccessor.OpenNHibernateSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(socialNetwork);
                    transaction.Commit();
                }
            }
        }
    }
}
